<?php
namespace oss;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Config;
use think\Log;

class QiniuCloud {
    private static $config;

    /**
     * @return null
     * @throws \Exception
     */
    public static function upload($key,$file){
        self::$config = Config::get('qiniu');
        $auth = new Auth(self::$config['accessKey'],self::$config['secretKey']);
        $token = $auth->uploadToken(self::$config['bucket']);

        $uploadMgr = new UploadManager();

        list($ret,$err) = $uploadMgr->putFile($token,$key,$file);
        if($err !== null){
            return null;
        }else{
            return $ret['key'];
        }
    }

    /**
     * 微信声音+转码
     * @param $key
     * @param $file
     * @return null
     * @throws \Exception
     */
    public static function uploadWxVoice($key,$file){
        self::$config = Config::get('qiniu');
        $auth = new Auth(self::$config['accessKey'],self::$config['secretKey']);
        $pipeline = 'aitelover_voice';
        //转码
        $fname = str_replace(".amr",".mp3",$key);
        $savekey = \Qiniu\base64_urlSafeEncode(self::$config['bucket'] . ":".$fname);
        $fops = "avthumb/mp3/ab/192k/ar/44100/acodec/libmp3lame";
        $fops = $fops.'|saveas/'.$savekey;
        $policy = array(
            'persistentOps' => $fops,
            'persistentPipeline' => $pipeline
        );
        $token = $auth->uploadToken(self::$config['bucket'],null, 3600, $policy);
        $uploadMgr = new UploadManager();
        list($ret,$err) = $uploadMgr->putFile($token,$key,$file);

        if($err !== null){
            return null;
        }else{
            //return $ret['key'];
            return $fname;
        }
    }
}